import re

from loguru import logger

from com.arcfox.manager.redis_task_manager import RedisTaskManager
from com.arcfox.middleware import async_mysql_middleware as db
from com.arcfox.school.processor.base_processor import BaseProcessor
from com.arcfox.util.muilty_coroutine_util import concurrency
from com.arcfox.util.redis_key_manager import HAND_UNIVERSITY_SCHOOL_LIST_KEY


class HandEnrollmentPlanProcessor(BaseProcessor):
    def __init__(self):
        self.task_manager = RedisTaskManager(HAND_UNIVERSITY_SCHOOL_LIST_KEY)

    async def parse_and_save_data(self, task, province_name, result_json):
        logger.info(result_json)
        result_data = result_json['data']
        tasks = []
        logger.info(result_data)
        for item in result_data['item']:
            major_year = item['length']  # 四年
            subject_name = ''
            if 'level2_name' in item:
                subject_name = item['level2_name']  # 法学 文学
            plan_batch = item['local_batch_name']  # 本科批
            plan_category = item['local_type_name']  # 物理类, 文科
            plan_count = item['num']  # 3 招生人数
            subject_requirement = ''
            if 'sg_info' in item:
                subject_requirement = item['sg_info']  # 首选物理，再选不限
            major_group = item['sg_name']  # 专业2组
            plan_major_name = item['spname']  # 本科预科班（办学地点：湖南省长沙市，外语要求：不限。）, 新闻传播学类（办学地点：湖南省长沙市，外语要求：不限。）
            if not plan_major_name:
                continue
            plan_major_code = ''
            if "spcode" in item:
                plan_major_code = item['spcode']  # 专业代码 020401
            major_fee = str(item['tuition'])
            plan_year = item['year']
            tasks.append({
                "university_uid": task['uid'], "university_name": task['name'],
                "major_year": major_year, "subject_name": subject_name,
                "plan_batch": plan_batch, "plan_category": plan_category,
                "plan_count": str(plan_count), "province_name": province_name,
                "subject_requirement": subject_requirement, "major_group": major_group,
                "plan_major_name": plan_major_name, "plan_major_code": plan_major_code,
                "major_fee": major_fee, "plan_year": plan_year, "major_name": self.process_major_name(plan_major_name)
            })
        await self.__save(tasks=tasks)

    def process_major_name(self, plan_major_name):
        if plan_major_name:
            results = re.split(r'[(（]', plan_major_name)
            major_name = results[0]
            # logger.info(f"before: {plan_major_name} after: {major_name}")
            return major_name
        return None

    @concurrency(5)
    async def __save(self, **params):
        task = params['task']
        mapping = db.MysqlMapping("tb_enrollment_plan")
        select_data = {
            "university_uid": task['university_uid'], "province_name": task['province_name'],
            "plan_year": task['plan_year'], "plan_batch": task['plan_batch'], "major_year": task['major_year'],
            "plan_category": task['plan_category'], "plan_major_name": task['plan_major_name']
        }
        if task['major_group']:
            select_data['major_group'] = task['major_group']
        old_data = await mapping.query(select_data, ["id"])
        if old_data:
            logger.info("{}数据已存在!{}", old_data[0][0], task)
        else:
            await mapping.insert(task)
